<?php

/**
 * alltosun.com  订单方面接口
 * ============================================================================
 * 版权所有 (C) 2009-2015 北京互动阳光科技有限公司，并保留所有权利。
 * 网站地址: http://www.alltosun.com
 * ----------------------------------------------------------------------------
 * 许可声明: 这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
 * ============================================================================
 * $Author: 张元昊 (zhangyh@alltosun.com) $
 * $Date: 2015-11-30 17:24:44 $
 * $Id$
 */
class Action
{

    private $per_page = 50;

    private $token = '';
    private $user_id = 0;
    private $user_info = array();
    private $api_stat_id = 0;

    public function __construct() {
        $this->token = an_request('token');

        if ($this->token) {
            $user_info = user_helper::get_user_info_by_token($this->token);
            if ($user_info && $user_info['status'] == 1) {
                $this->user_id = $user_info['id'];
                $this->user_info = $user_info;
            }
        }
    }

    /**
     * 获取支付方式列表
     */
    public function get_pay_type_list() {
        $list = _widget('order')->get_pay_type_list($this->user_info);
        api_helper::return_data(0, 'success', $list);
    }

    /**
     * 订单是否已收款
     */
    public function change_order_pay_status() {
        $order_id = an_request('order_id', 0, 'post');
        $is_pay = an_request('is_pay', 1, 'post');

        //加密参数
        $sign_param = array(
            'order_id' => $order_id, // 订单号
            'is_pay' => $is_pay, // 是否收款
        );
        // 验证接口
        api_helper::check_sign($sign_param, 1);

        $decode_order_id = order_helper::order_id_decode($order_id);

        $result = _widget('order')->change_order_pay_status($this->user_id, $decode_order_id, $is_pay);

        if ($result['flag']) {
            api_helper::return_data(0, $result['info']);
        } else {
            api_helper::return_data(1, $result['info']);
        }


    }

    // 获取订单列表
    // For 合伙人
    public function get_store_order_list() {

        $store_id = an_request('store_id');

        $page_no = an_request('page_no');

        $progress = an_request('progress');

        //加密参数
        $sign_param = array(
            'page_no' => $page_no,
            'store_id' => $store_id,
            'progress' => $progress
        );

        // 验证接口
        api_helper::check_sign($sign_param, 1);

        $store_info = _uri('store', $store_id);

        if (!$store_info || $store_info['status'] == 0) {
            api_helper::return_data(1, '商户不存在或者已删除');
        }

        if ($store_info['user_id'] != $this->user_id && $store_info['owner_id'] != $this->user_id) {
            api_helper::return_data(1, '商户所属用户与登录用户不符');
        }

        $filter = array(
            'store_id' => $store_id,
            'status' => 1
        );

        // 最大兼容
        $progress_list = array_merge(order_config::$dealer_progress, order_config::$dealer_progress_old, order_config::$store_progress);
        if ($progress) {
            $progress = explode(',', $progress);
            $progress_arr = array();
            foreach ($progress as $item) {
                if (!array_key_exists($item, $progress_list)) {
                    api_helper::return_data(1, '没有此订单状态');
                }
                $progress_arr = array_merge($progress_arr, order_config::dealer_progress_o2n_filter($item));
            }
            $filter['progress'] = $progress_arr;
        } else {
            $filter['progress !='] = order_config::DEALER_CANCEL;
        }

        $order_count = _model('order')->getTotal($filter);
        if (empty($order_count)) {
            api_helper::return_data(0, 'success', array('order_list' => array()));
        }

        $pager = new Pager($this->per_page);
        $order_list = _model('order')->getList($filter, 'ORDER BY `id` DESC ' . $pager->getLimit($page_no));
        foreach ($order_list as $key => $item) {
            $order_list[$key]['id'] = order_helper::order_id_encode($item['id']);
            $order_list[$key]['price'] = num_keep_two_round($item['price']);
            $order_list[$key]['goods_type_num'] = order_helper::get_order_goods_total_by_id($item['id']);

            $cur_order_info = order_helper::get_order_info($item['id']);
            $order_list[$key]['bbcoin'] = $cur_order_info['bbcoin'];
            $order_list[$key]['is_bbcoin_enable'] = $cur_order_info['is_bbcoin_enable'];

            $order_list[$key]['progress'] = order_config::dealer_progress_n2o($item['progress']);

        }

        api_helper::return_data(0, 'success', array(
            'order_list' => $order_list,
        ));
    }

    // 获取订单列表
    // For 终端
    public function get_order_list() {
        $store_id = an_request('store_id');
        $page_no = an_request('page_no', 1);
        $progress = an_request('progress');
        $time_condition = an_request('time_condition');

        //加密参数
        $sign_param = array(
            'page_no' => $page_no,
            'store_id' => $store_id,
            'progress' => $progress,
            'time_condition' => $time_condition
        );
        // 验证接口
        $this->api_stat_id = api_helper::check_sign($sign_param, 1);

        //如果是总店则查询旗下分店的订单
        $store_ids = '';
        if ($store_id) {//分店
            $store_info = _uri('store', $store_id);
            if (!$store_info || $store_info['status'] == 0) {
                api_helper::return_data(1, '商户不存在或者已删除');
            }
            if ($store_info['user_id'] != $this->user_id && $store_info['owner_id'] != $this->user_id) {
                api_helper::return_data(1, '商户所属用户与登录用户不符');
            }
        } else {
            if ($this->user_info['role_type'] == user_config::STORE_OWNER) {//总店
                $store_ids = store_helper::get_store_ids_by_owner_id($this->user_id, array(
                    'status !=' => 0,
                    'is_enable' => 1
                ));
                $store_ids = $store_ids ? $store_ids : -1;
            } else {
                api_helper::return_data(1, '请选择一个店铺');
            }
        }

        $store_id = ($store_ids != '' && $store_ids != -1) ? $store_ids : $store_id;
        $filter = array(
            'store_id' => $store_id,
            'status' => 1,
            'is_enable' => 1
        );
        $progress_list = order_config::$store_progress;
        if ($progress) {
            $progress_arr = explode(',', $progress);
            foreach ($progress_arr as $key => $value) {
                if (!$progress_list[$value]) {
                    api_helper::return_data(1, '没有此订单状态');
                }
                $progress_arr[$key] = (int)$value;
            }
            $filter['progress'] = $progress_arr;
        }

        if ($time_condition) {
            switch ($time_condition) {
                case 1:
                    $filter['add_time >='] = datetime(strtotime('now -1 month'), 'Y-m-d 00:00:00');
                    $filter['add_time <='] = datetime();
                    break;
                case 2:
                    $filter['add_time >='] = datetime(strtotime('now -3 month'), 'Y-m-d 00:00:00');
                    $filter['add_time <='] = datetime();
                    break;
                case 3:
                    $filter['add_time >='] = datetime(strtotime('now -6 month'), 'Y-m-d 00:00:00');
                    $filter['add_time <='] = datetime();
                    break;
                case 4:
                    $filter['add_time <='] = datetime(strtotime('now -6 month'), 'Y-m-d 00:00:00');
                    break;
                default:
            }
        }

        //统计几种订单数量
        /*
             $count_filter = $filter;
             //正在进行中的
             $count_filter['progress'] = array(1, 5);
             $count_order_ing = _model('order')->getTotal($count_filter);

             //配送中
             $count_filter['progress'] = array(5);
             $count_order_deliver = _model('order')->getTotal(enable_filter($count_filter));

             //配送完成
             $count_filter['progress'] = 10;
             $count_order_finish = _model('order')->getTotal(enable_filter($count_filter));

             //撤单
             $count_filter['progress'] = 15;
             $count_order_cancel = _model('order')->getTotal(enable_filter($count_filter));
         */
        $curr_order_count = _model('order')->getTotal(enable_filter($filter));
        if (!$curr_order_count) {
            api_helper::return_data(0, 'success', array('order_list' => array()), $this->api_stat_id);
        }

        $pager = new Pager($this->per_page);
        $curr_order_list = _model('order')->getList(enable_filter($filter), 'ORDER BY `id` DESC ' .
                                                                            $pager->getLimit($page_no));
        foreach ($curr_order_list as $key => $value) {
            $curr_order_list[$key]['id'] = order_helper::order_id_encode($value['id']);
            $curr_order_list[$key]['price'] = format_money($value['price']);
            $curr_order_list[$key]['goods_type_num'] = order_helper::get_order_goods_total_by_id($value['id']);
            if (isset($store_info) && $store_info) {
                $curr_order_list[$key]['store_title'] = $store_info['title'] . $store_info['title_branch'];
            } else {
                $curr_order_list[$key]['store_title'] = store_helper::get_store_title($value['store_id']);
            }

            // 处理支付凭证信息
            if (!$value['payoff_person']) {
                $curr_order_list[$key]['payoff_person'] = '暂无';
            }
            if (!$value['payoff_time'] || $value['payoff_time'] == '0000-00-00 00:00:00') {
                $curr_order_list[$key]['payoff_time'] = '暂无';
            }
            if (!$value['payoff_extra']) {
                $curr_order_list[$key]['payoff_extra'] = '暂无';
            }

            $cur_order_info = order_helper::get_order_info($value['id']);
            $curr_order_list[$key]['bbcoin'] = $cur_order_info['bbcoin'];
            $curr_order_list[$key]['is_bbcoin_enable'] = $cur_order_info['is_bbcoin_enable'];
        }
        api_helper::return_data(0, 'success', array(
            'order_list' => $curr_order_list,/*
            'count_order_ing' => $count_order_ing,
            'count_order_deliver' => $count_order_deliver,
            'count_order_finish' => $count_order_finish,
            'count_order_cancel' => $count_order_cancel*/
        ), $this->api_stat_id);
    }

    //获取订单详情
    public function get_order_detail() {

        $store_id = an_request('store_id');
        $order_id = an_request('order_id');

        //加密参数
        $sign_param = array(
            'store_id' => $store_id,
            'order_id' => $order_id
        );
        // 验证接口
        api_helper::check_sign($sign_param, 1);

        if (!$store_id) {
            api_helper::return_data(1, '商户ID无效');
        }
        $store_info = store_helper::get_store($store_id);

        if (!$store_info || $store_info['status'] == 0) {
            api_helper::return_data(1, '商户不存在或者已删除');
        }

        //获取总店信息
        $user_store_info = store_helper::get_user_store($store_info['owner_id']);

        if (!$order_id) {
            api_helper::return_data(1, '订单ID无效');
        }

        $order_decode_id = order_helper::order_id_decode($order_id);

        if (!is_numeric($order_decode_id)) {
            api_helper::return_data(1, $order_decode_id);
        }

        $order_info = order_helper::get_order_info($order_decode_id);

        if (!$order_info || !$order_info['status']) {
            api_helper::return_data(1, '订单不存在或者已经删除');
        }

        //xdq 储存order_info里的is_pay，一会$order_info就被覆盖了？
        $is_pay = $order_info['is_pay'];
        $order_id = $order_info['id'];
        /**
         * 1、当用户不属于订单的门店
         * 2、当前用户不属于总店的用户，总店是第一家分店的订单
         * 2、当前用户不属于订单的合伙人
         * 3、当前订单不属于订单的分派人的订单
         * 4、当前订单不属于合伙人旗下的订单
         */
        if ($store_info['user_id'] != $this->user_id &&
            $store_info['owner_id'] != $this->user_id &&
            $store_info['agency_id'] != $this->user_id &&
            $order_info['assigned_id'] != $this->user_id &&
            $order_info['agency_id'] != $this->user_id
        ) {
            api_helper::return_data(1, '此订单您无权限操作');
        }

        if ($order_info['type'] == 1) {
            //查询合伙人信息
            $order_info['progress'] = order_config::dealer_progress_n2o($order_info['progress']);
        }

        $order_info = _widget('order')->get_order_detail($order_info, $store_info['id'], $user_store_info['addon_price']);
        if (!$order_info) {
            api_helper::return_data(1, '订单信息有误');
        }

        // TODO pay 计算实际支付金额
        $order_info['actual_payment'] = array(
            array('type' => 'bbcoin', 'value' => $order_info['pay_bbcoin'], 'name' => '抱抱币'),
            array('type' => 'balance', 'value' => $order_info['pay_user_money'], 'name' => '余额'),
        );

        $order_info['actual_price'] = num_keep_two_round($order_info['price'] - $order_info['pay_user_money']);


        //xdq add 2016-07-13
        $delivery_status = order_helper::get_order_delivery_note_status_by_order_id($order_id);
        if (isset($delivery_status)) {
            // 如果是预审核显示为待审
            if ($delivery_status == '5') {
                $delivery_status = '1';
            }
            $order_info['delivery_note_status'] = $delivery_status;
        } else {
            $order_info['delivery_note_status'] = null;
        }

        $order_info['is_pay'] = $is_pay;

        // 返回服务器时间
        $order_info['server_time'] = datetime();

        //店铺信息 author:xiaolin date:2016-10-15
        $order_info['store_info'] = $store_info;

        api_helper::return_data(0, 'success', $order_info);
    }

    //检查订单是否有正在进行中的
    public function check_order() {
        $store_id = an_request('store_id');

        //加密参数
        $sign_param = array(
            'store_id' => $store_id
        );
        // 验证接口
        api_helper::check_sign($sign_param, 1);

        if (!$store_id) {
            api_helper::return_data(1, '商户ID无效');
        }
        $store_info = _uri('store', $store_id);

        if (!$store_info || $store_info['status'] == 0) {
            api_helper::return_data(1, '商户不存在或者已删除');
        }

        if ($store_info['user_id'] != $this->user_id && $store_info['owner_id'] != $this->user_id) {
            api_helper::return_data(1, '商户所属用户与登录用户不符');
        }

        return api_helper::return_data(0, 'success', array('is_order_ing' => 0));

        $order_id = order_helper::check_order_ing($store_id);
        if ($order_id) {
            api_helper::return_data(0, 'success', array(
                'is_order_ing' => 1,
                'order_id' => order_helper::order_id_encode($order_id)
            ));
        } else {
            api_helper::return_data(0, 'success', array('is_order_ing' => 0));
        }
    }

    /**
     * 门店下单
     *
     * @throws AnException
     */
    public function trade_order() {

        // 商品列表
        $order_goods_list = an_request('order_goods_list', '', 'request', 0);

        // 门店id
        $store_id = an_request('store_id');

        // 价格
        $price = an_request('price');

        // 手机
        $mobile = an_request('mobile');

        // 支付类型
        $pay_type = an_request('pay_type');

        // 送货类型
        $deliver_type = an_request('deliver_type');

        // 订单类型
        $order_type = an_request('order_type');

        // $cup_type = an_request('cup_type');
        // 杯体列表
        $cup_list = an_request('cup_list', '', 'request', 0);

        // 版本号
        $app_version = an_request('v', 0);

        // xdq add 2016-07-13
        $is_ious = an_request('is_ious', 0);

        // shinate 2016-07-21
        $user_money = an_request('user_money', '0.00');
        $is_user_money = an_request('is_user_money', 0);
        $bbcoin = an_request('bbcoin', '0.0');

        // 抱抱币兑换 shinate 2016-08-01
        $bbcoin_price = an_request('bbcoin_price', '0');
        $order_bbcoin_exchange_list = an_request('order_bbcoin_exchange_list', '', 'request', 0);

        if ($app_version > 1.6) {
            $note = an_request('note');
        } else {
            $note = Request::Post('note');
        }

        // $cup_type_list = goods_config::$cup_type;

        //加密参数
        $sign_param = array(
            'order_goods_list' => $order_goods_list,
            'store_id' => $store_id,
            'price' => $price,
            'mobile' => $mobile,
            'pay_type' => $pay_type,
            'deliver_type' => $deliver_type,
            'order_type' => $order_type,
            'cup_list' => $cup_list,
            'is_ious' => $is_ious,
            'bbcoin' => $bbcoin,
            'is_user_money' => $is_user_money,
            'user_money' => $user_money,
            'note' => $note,
            'bbcoin_price' => $bbcoin_price,
            'order_bbcoin_exchange_list' => $order_bbcoin_exchange_list,
        );

        //验证密钥
        api_helper::check_sign($sign_param, 1);

        if (!$order_goods_list) {
            api_helper::return_data(1, '请传递商品具体信息参数');
        }
        $order_goods_list = json_decode($order_goods_list, true);

        if (!$store_id) {
            api_helper::return_data(1, '商户ID无效');
        }
        $store_info = _uri('store', $store_id);

        if (!$store_info || $store_info['status'] == 0) {
            api_helper::return_data(1, '商户不存在或者已删除');
        }

        // 不是分店店长且不是总店店长
        if ($store_info['user_id'] != $this->user_id && $store_info['owner_id'] != $this->user_id) {
            api_helper::return_data(1, '您不能帮此店铺进货');
        }
        // 获取总店信息
        $user_store_info = _uri('user_store', array('user_id' => $store_info['owner_id']));

        if (order_helper::check_order_ing($store_id)) {
            // @wangdk 允许门店同时进货
            // api_helper::return_data(1, '已经有正在进行的订单，不允许再次下单');
        }

        $user_info = user_helper::get_user_info($store_info['user_id']);

        // 余额校验
        if ($is_user_money == 1) {
            $user_money = floatval($user_money);
            if ($user_money !== floatval($user_info['user_money'])) {
                api_helper::return_data(1, '您的余额发生了变化，请重新下单', array(
                    'user_money' => $user_info['user_money'],
                    'bbcoin' => $user_info['bbcoin']
                ));
            }
        }

        if (!empty($order_bbcoin_exchange_list)) {
            $bbcoin = intval($bbcoin);
            if ($bbcoin !== intval($user_info['bbcoin'])) {
                api_helper::return_data(1, '您的抱抱币发生了变化，请重新下单', array(
                    'user_money' => $user_info['user_money'],
                    'bbcoin' => $user_info['bbcoin']
                ));
            }
        }

        // 查询合伙人信息
        $agency_store_info = _uri('store', array('user_id' => $store_info['agency_id']));

        // 总额
        $order_price_sum = 0.00;

        // 总数量
        $order_goods_num = 0;

        // 散装商品数量
        $order_bulk_goods_num = 0;

        // 下单商品列表
        $order_data = array();

        // 计算商品价格
        foreach ($order_goods_list as $k => $v) {
            $goods_info = _uri('goods', $v['goods_id']);

            //             if(!$goods_info || !$goods_info['status']) {
            //                 api_helper::return_data(1, '包含商品不存在');
            //             }
            //             if(!$goods_info['is_sale']) {
            //                 api_helper::return_data(1, '包含商品还未上架');
            //             }

            $filter = array(
                'sku_id' => $v['sku_id'],
                'goods_id' => $v['goods_id'],
            );

            $filter['store_id'] = $user_store_info['id'];

            // 获取总店的SKU定价
            $store_goods_sku_info = _uri('store_goods_sku', $filter);

            if (!$store_goods_sku_info) {
                // 先屏蔽下架判断
                // if(!$store_goods_sku_info['status']) {
                //     api_helper::return_data(1, '包含商品不存在或者已经下架');
                // }
                // 获取合伙人的SKU定价
                $agency_user_store_info = _uri('user_store', array('user_id' => $agency_store_info['user_id']));
                $filter['store_id'] = $agency_user_store_info['id'];
                $store_goods_sku_info = _uri('store_goods_sku', $filter);
            }
            // 算出单件商品的总价格
            if ($store_goods_sku_info) {
                $tmp_price = ($store_goods_sku_info['price'] + $user_store_info['addon_price']) * $v['goods_num'];
            } else {
                api_helper::return_data(1, '包含商品信息有误');
            }

            $order_price_sum = $order_price_sum + $tmp_price;

            // 先构建order_relation_info数据结构
            $order_data[] = array(
                'user_id' => $store_info['user_id'],
                'goods_id' => $v['goods_id'],
                'sku_id' => $v['sku_id'],
                'goods_num' => $v['goods_num'],
                'addon_price' => $user_store_info['addon_price'],
                'goods_price' => $store_goods_sku_info['price'],
                'real_price' => $tmp_price,
            );

            //判断是否有散装商品，计算杯的数量
            if ($goods_info['category_id'] == goods_config::CATEGORY_BULK) {
                $order_bulk_goods_num = $order_bulk_goods_num + $v['goods_num'];
            }
            $order_goods_num = $order_goods_num + $v['goods_num'];
        }

        //格式化价钱 保留两位小数
        $order_price_sum = num_keep_two_round($order_price_sum);

        if (!$price) {
            api_helper::return_data(1, '订单总价格无效');
        }
        // api_helper::return_data(1, $order_price_sum);

        // TODO 丢失精度问题临时解决
        $o_price = floatval($price);
        $n_price = round($o_price * 10) / 10;

        if ($o_price !== $n_price) {
            $price = $n_price;
        }

        if ($order_price_sum != num_keep_two_round($price)) {
            api_helper::return_data(1, '订单总价格不正确');
        }

        $pay_type_list = order_config::$pay_type_list;
        if (!$pay_type || !$pay_type_list[$pay_type]) {
            api_helper::return_data(1, '支付方式无效');
        }

        $deliver_type_list = order_config::$deliver_type;

        if (!$deliver_type || !$deliver_type_list[$deliver_type]) {
            api_helper::return_data(1, '配送方式无效');
        }

        if (!$mobile || !user_helper::is_mobile($mobile)) {
            api_helper::return_data(1, '手机号无效或者手机号格式不正确');
        }

        $order_type_list = order_config::$order_type;
        if (!$order_type || !$order_type_list[$order_type]) {
            api_helper::return_data(1, '订单类型无效');
        }

        // 处理兑换 shiante 2016-08-01
        $order_exchange_data = array();
        $order_exchange_num = 0;
        $order_exchange_bbcoin_sum = 0;
        if (!empty($order_bbcoin_exchange_list)) {

            $exange_list = json_decode($order_bbcoin_exchange_list, 1);

            if (!empty($exange_list)) {

                foreach ($exange_list as $item) {

                    // $goods_info = goods_helper::get_goods_info($item['goods_id']);

                    $filter = array(
                        'sku_id' => $item['sku_id'],
                        'goods_id' => $item['goods_id'],
                    );

                    $filter['store_id'] = $user_store_info['id'];

                    // 获取总店的SKU定价
                    $store_goods_sku_info = _uri('store_goods_sku', $filter);

                    if (!$store_goods_sku_info) {
                        // 获取合伙人的SKU定价
                        $agency_user_store_info = _uri('user_store', array('user_id' => $agency_store_info['user_id']));
                        $filter['store_id'] = $agency_user_store_info['id'];
                        $store_goods_sku_info = _uri('store_goods_sku', $filter);
                    }

                    // TODO bbcoin 向上取整
                    $store_goods_sku_bbcoin = ceil($store_goods_sku_info['price']);

                    // 算出单件商品的总价格
                    if ($store_goods_sku_info) {
                        $tmp_price = $store_goods_sku_bbcoin * $item['goods_num'];
                    } else {
                        api_helper::return_data(1, '兑换的商品中包含有误的商品信息');
                    }

                    // 计算兑换商品总数
                    $order_exchange_num += $item['goods_num'];
                    // 总抱抱币累计
                    $order_exchange_bbcoin_sum += $tmp_price;

                    // 构建order_exchange_info 数据结构
                    $order_exchange_data[] = array(
                        'user_id' => $this->user_id,
                        'goods_id' => $item['goods_id'],
                        'sku_id' => $item['sku_id'],
                        'goods_num' => $item['goods_num'],
                        'goods_price' => $store_goods_sku_bbcoin,
                        'real_price' => $store_goods_sku_bbcoin * $item['goods_num'],
                        'exchange_type' => isset($item['exchange_type']) ? $item['exchange_type'] : 'bbcoin'
                    );
                }
            }
        }

        if (intval($order_exchange_bbcoin_sum) != intval($bbcoin_price)) {
            api_helper::return_data(1, '兑换总价格不正确');
        }

        // 处理散装商品杯型
        if ($order_bulk_goods_num) {
            if (!$cup_list) {
                api_helper::return_data(1, '请传递散装商品具体信息参数');
            }
            $cup_list = json_decode($cup_list, true);
            $tmp_box_sum = 0;
            $cup_config_list = cup_config::$cup_type;
            //组装信息格式
            $box_type_box = array();
            foreach ($cup_list as $k => $v) {
                if (!isset($v['box_num']) || !$v['box_num']) {
                    unset($cup_list[$k]);
                    continue;
                }

                //计算此杯型数目
                $tmp_box_sum = $tmp_box_sum + $v['box_num'];

                //过滤掉不正确的杯型
                if (!$cup_config_list[$v['cup_type']]) {
                    api_helper::return_data(1, '散装商品杯型信息有误');
                }

                $box_type_box[$v['cup_type']] = $v['box_num'];
            }

            // 判断散装商品数量和总箱子数量是否吻合
            if ($tmp_box_sum != $order_bulk_goods_num) {
                api_helper::return_data(1, '散装商品数量信息错误');
            }
            //查询订单数目
            // $order_num = order_helper::get_store_order_num($store_id);
            // if($order_num > 3) {
            //     $is_double = 0;
            // } else {
            //     $is_double = 1;
            // }
            $cup_list = cup_config::$cup_type;
            $cup_num_data = cup_helper::get_app_dealer_cup_num($store_id, $order_bulk_goods_num, $box_type_box, 0, 1);
            foreach ($cup_num_data as $key => $value) {
                if ($value['store_cup_num'] < $value['cup_num']) {
                    api_helper::return_data(1, $cup_list[$key] . '库存不够，无法提交订单');
                }
            }
        }

        $info = array(
            'type' => $order_type,
            'price' => $order_price_sum,
            'user_id' => $store_info['user_id'],
            'store_id' => $store_id,
            'mobile' => $mobile,
            'deliver_type' => $deliver_type,
            'pay_type' => $pay_type,
            'goods_num' => $order_goods_num,
            'agency_id' => $store_info['agency_id'],
            'marketing_id' => $store_info['marketing_id'],
            'exchange_num' => $order_exchange_num,
            'pay_bbcoin' => $order_exchange_bbcoin_sum,
        );

        if ($note) {
            $info['note'] = $note;
        }

        $return_score_data = _widget('score_record')->format_store_order_score($store_id, $order_goods_num, $order_price_sum);

        if ($return_score_data) {
            $info['score'] = $return_score_data['score'];
        }

        // 测试账号标记
        if (user_helper::is_test_dealers_user($store_info['agency_id'])) {
            $info['is_enable'] = 0;
        }

        // 使用余额支付
        if ($is_user_money == 1 && $user_info['user_money'] > 0) {
            $real_user_money = floatval($user_info['user_money']);
            $order_price_sum = floatval($order_price_sum);
            $pay_user_money = $order_price_sum >= $real_user_money ? $real_user_money : $order_price_sum;
            // $pay_cash = $order_price_sum - $pay_user_money;
            $info['pay_user_money'] = $pay_user_money;

            // 只要和公司结款就要开启白条, 白了多少, 财务来审核
            $info['is_pay'] = 0;
            $info['is_ious'] = 1;
        }

        // 如果是白条支付
        if ($is_ious == 1) {
            if ($store_info['is_allow_credit'] == 1) {
                $info['is_pay'] = 0;
                $info['is_ious'] = 1;
            } else {
                api_helper::return_data(1, '无法使用白条支付, 请及时确认');  //xdq tmp
            }
        }

        $order_id = _model('order')->create($info);
        if (!$order_id) {
            api_helper::return_data(1, '网络原因，提交订单失败');
        }

        if ($order_id) {

            // 成功再扣余额
            if (isset($info['pay_user_money']) && $info['pay_user_money'] > 0) {
                user_money_helper::change_user_money(array(
                    'user_id' => $user_info['id'],
                    'user_money' => -1 * $info['pay_user_money'],
                    'order_id' => $order_id,
                ));
                $user_info['user_money'] = _uri('user', $store_info['user_id'], 'user_money');
            }

            // 成功再扣抱抱币
            if (isset($info['pay_bbcoin']) && $info['pay_bbcoin'] > 0) {
                bbcoin_helper::change_bbcoin(array(
                    'user_id' => $user_info['id'],
                    'res_id' => bbcoin_config::RES_TYPE_EXCHANGE,
                    'bbcoin' => -1 * $info['pay_bbcoin'],
                    'order_id' => $order_id,
                ));
                $user_info['bbcoin'] = _uri('user', $store_info['user_id'], 'bbcoin');
            }

            //构架order_relation 关联表
            if (!empty($order_data)) {
                foreach ($order_data as $item) {
                    $item['order_id'] = $order_id;
                    _model('order_relation')->create($item);
                }
            }

            // 兑换表关联
            if (!empty($order_exchange_data)) {
                foreach ($order_exchange_data as $item) {
                    $item['order_id'] = $order_id;
                    // $item['add_time'] = datetime();
                    _model('order_exchange_relation')->create($item);
                }
            }

            // 增加到订单的分支表中
            $order_branch_id = order_helper::create_order_branch($order_id, $this->user_info, $store_info);

            if ($order_bulk_goods_num) {
                // 创建杯型数据
                $return_data = cup_helper::save_cup_record($order_id, $store_id, $cup_num_data, 1);
            }

            // 如果是赊账，或者影院，需要插入送货单表
            // 2016-07-15 蒙确认 私人影吧 105 不强制上传
            // 2016-08-04 田鹏确认 只要和公司有金钱关系的, ious从此, 代表"和公司结账"
            if (isset($info['is_ious']) && $info['is_ious'] == 1) {
                //默认'status' => 0
                order_helper::create_order_delivery_note_by_order_id($order_id);
            }

            // 设置了自动委派合伙人
            if ($store_info['service_agency_id'] > 0) {
                order_helper::set_order_service_agency($order_id, $store_info['service_agency_id']);
            }

            $order_id_encode = order_helper::order_id_encode($order_id);
            _widget('order.message')->trade_order_message($order_id_encode, $store_info);

            api_helper::return_data(0, 'success', array(
                'order_id' => $order_id_encode,
                'user_money' => $user_info['user_money'],
                'bbcoin' => $user_info['bbcoin'],
            ));
        } else {
            api_helper::return_data(1, '网络原因，提交订单失败');
        }
    }

    /**
     * 更改订单状态
     * 仅作用于终端订单!
     * 代码未剥离
     *
     * @throws AnException
     */
    public function update_order_progress() {
        $store_id = an_request('store_id');
        $order_id = an_request('order_id');
        $progress = an_request('progress');
        $reason = an_request('reason');

        //加密参数
        $sign_param = array(
            'store_id' => $store_id,
            'order_id' => $order_id,
            'progress' => $progress,
            'reason' => $reason
        );

        //验证密钥
        api_helper::check_sign($sign_param, 1);

        $order_info = _uri('order', order_helper::order_id_decode($order_id));

        if ($order_info['type'] == 1) {
            api_helper::return_data(1, '无法处理此类订单');
        }

        $result = _widget('order')->update_order_progress($order_id, $progress, $reason, $this->user_info);

        if ($result['flag']) {
            api_helper::return_data(0, $result['info']);
        } else {
            api_helper::return_data(1, $result['info']);
        }
    }

    // 获取上一次订单信息
    public function get_prev_order_detail() {
        $store_id = an_request('store_id');

        //加密参数
        $sign_param = array(
            'store_id' => $store_id
        );
        //验证密钥
        api_helper::check_sign($sign_param, 1);

        if (!$store_id) {
            api_helper::return_data(1, '商户ID无效');
        }

        $store_info = _uri('store', $store_id);

        if (!$store_info || $store_info['status'] == 0) {
            api_helper::return_data(1, '商户不存在或者已删除');
        }

        if ($store_info['user_id'] != $this->user_id && $store_info['owner_id'] != $this->user_id) {
            api_helper::return_data(1, '商户所属用户与登录用户不符');
        }

        //获取总店信息
        $user_store_info = _uri('user_store', array('user_id' => $store_info['owner_id']));

        //查询合伙人信息
        $agency_store_info = _uri('store', array('user_id' => $store_info['agency_id']));

        $order_info_desc = _model('order')->read(array('status' => 1, 'store_id' => $store_id), ' ORDER BY `id` DESC');

        //如果没有进过货  则返回空数组
        if (!$order_info_desc) {
            api_helper::return_data(0, 'success', array());
        }

        $order_relation_list = _model('order_relation')->getList(array('order_id' => $order_info_desc['id']));

        foreach ($order_relation_list as $key => $value) {
            $filter = array(
                'store_id' => $agency_store_info['id'],
                'goods_id' => $value['goods_id']
            );
            $store_goods_info = _uri('store_goods', $filter);
            if ($store_goods_info) {
                $goods_info = _uri('goods', $store_goods_info['goods_id']);
                if ($goods_info['cover']) {
                    $cover_path = _uri('attachment', $goods_info['cover'], 'path');
                    $goods_info['cover'] = _image($cover_path, 'list');
                }
                $goods_info['category_name'] = _uri('category', $goods_info['category_id'], 'title');

                $order_relation_list[$key]['goods_info'] = $goods_info;

                $order_relation_list[$key]['goods_info']['sku_list'] = goods_helper::get_store_sku_list($store_info['id'], $store_goods_info['goods_id'], $user_store_info['addon_price']);
            }
        }
        $order_info_desc['order_relation_list'] = $order_relation_list;
        //添加杯型数据
        $order_cup_list = _model('order_cup')->getList(array('order_id' => $order_info_desc['id']));
        $order_info_desc['order_cup_list'] = $order_cup_list;
        //对订单ID进行编码
        $order_info_desc['id'] = order_helper::order_id_encode($order_info_desc['id']);
        api_helper::return_data(0, 'success', $order_info_desc);

    }

}